<template>
  <div>
    <div style="margin-bottom: 30px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>新闻后台管理</el-breadcrumb-item>
        <el-breadcrumb-item>个人信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="card">
      <el-card style="width: 500px;">
        <el-form style="margin-left: 80px;width: 255px;" label-width="80px" size="small">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8082/file/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-form-item label="账户">
            <el-input v-model="form.username" autocomplete="off" :disabled="true"></el-input>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="form.nickname" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="form.phone" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="form.address" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="save">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card style="width: 400px;height: 250px;margin-left: 25px;">修改密码
        <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" style="margin:25px 0 0 25px;width: 255px;"
                 label-width="70px" size="small">
          <el-form-item label="新密码" prop="pass">
            <el-input v-model="ruleForm.pass" autocomplete="off" show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input v-model="ruleForm.checkPass" autocomplete="off" show-password></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="savePassword('ruleForm')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>


  </div>
</template>

<script>
import pubsub from 'pubsub-js'
import {addOrUpdateUser, getUserByName} from '@/api/User'

export default {
  name: "Personal",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      rules: {
        pass: [
          {validator: validatePass, trigger: 'blur'}
        ],
        checkPass: [
          {validator: validatePass2, trigger: 'blur'}
        ],
      },
      ruleForm: {
        pass: '',
        checkPass: '',
      },
      form: {},
      user: localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {}
    }


  },
  created() {
    this.getUser().then(res => {
      console.log(res)
      this.form = res
    })
  },
  methods: {

    async getUser() {
      return (await this.request.get("/user/username/" + this.user.username)).data
    },
    savePassword(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.form.password = this.ruleForm.pass
          this.save();
          this.$refs[formName].resetFields();
        } else {
          if (!this.ruleForm.pass) {
            this.$notify.error({
              title: '请输入密码再提交',
            });
          } else {
            this.$notify.error({
              title: '两次密码不一致',
              message: '请重新输入密码'
            });
          }
        }
      });
    },
    save() {
      addOrUpdateUser(this.form).then(res => {
        console.log(res)
        if (res.code === '200') {
          this.$notify.success({
            title: '保存成功',
          });
          // 更新浏览器存储的用户信息
          this.getUser().then(res => {
            console.log(res, 'username')
            res.token = JSON.parse(localStorage.getItem("user")).token
            localStorage.setItem("user", JSON.stringify(res))
            pubsub.publish("sendMsg");
          })

        } else {
          this.$message.error("保存失败")
        }
      })
    },
    handleAvatarSuccess(res) {
      this.form.avatarUrl = res
    }
  }
}
</script>

<style scoped>
.card {
  display: flex;
  align-items: flex-start;
}

.avatar-uploader {
  text-align: center;
  padding-bottom: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 138px;
  height: 138px;
  line-height: 138px;
  text-align: center;
}

.avatar {
  width: 138px;
  height: 138px;
  display: block;
}
</style>

